<template>
    <div class="app-container">
        <ViewLayoutSearchArea>
            <el-form ref="searchFormRef" :inline="true" :model="searchData">
                <el-form-item prop="name" label="名称">
                    <el-input v-model="searchData.name" placeholder="请输入关键词" />
                </el-form-item>
                <el-form-item prop="type" label="类型">
                    <el-select v-model="searchData.type" placeholder="请选择网站类型">
                        <el-option
                            v-for="item in tagOptionData"
                            :key="item.type"
                            :label="item.name"
                            :value="item.type"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                    <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </ViewLayoutSearchArea>
        <el-card v-loading="loading" shadow="never">
            <ViewLayoutToolbarArea>
                <div></div>
                <div>
                    <el-button type="primary" @click="handleAdd()">新建</el-button>
                </div>
            </ViewLayoutToolbarArea>
            <ViewLayoutTableArea>
                <el-table :data="tableData">
                    <el-table-column prop="name" label="名称" align="center" />
                    <el-table-column prop="type" label="类型" align="center">
                        <template #default="{row}">
                            {{ getTagType(row.type) }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="150" align="center">
                        <template #default="scope">
                            <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)"
                                >编辑</el-button
                            >
                            <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </ViewLayoutTableArea>
            <ViewLayoutPagerArea>
                <el-pagination
                    background
                    :layout="paginationData.layout"
                    :page-sizes="paginationData.pageSizes"
                    :total="paginationData.total"
                    :page-size="paginationData.pageSize"
                    :current-page="paginationData.currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </ViewLayoutPagerArea>
        </el-card>
        <!-- 新增/编辑 -->
        <el-dialog
            v-model="dialogVisible"
            :title="currentUpdateId === undefined ? '新建类型 ' : '编辑类型'"
            width="600"
            :close="resetForm"
        >
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item prop="name" label="名称">
                    <el-input v-model="formData.name" placeholder="请输入类型名称" />
                </el-form-item>
                <el-form-item prop="type" label="类型">
                    <el-select v-model="formData.type" placeholder="请选择类型">
                        <el-option
                            v-for="item in tagOptionData"
                            :key="item.type"
                            :label="item.name"
                            :value="item.type"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleCreate">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {reactive, ref, watch} from 'vue';
import {addTableDataApi, deleteTableDataApi, updateTableDataApi, getTableDataApi} from '@/api/type-management/index';
import {type GetTableData} from '@/api/type-management/types/type-management';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Search, Refresh} from '@element-plus/icons-vue';
import {
    ViewLayoutSearchArea,
    ViewLayoutToolbarArea,
    ViewLayoutTableArea,
    ViewLayoutPagerArea
} from '@/layout/components';
import {tagOptionData, enumTagType} from '@/constants/common';
import {usePagination} from '@/hooks/usePagination';

defineOptions({
    name: 'TypeManagement'
});

const searchData = reactive({
    name: '', // 名称
    type: '' // 类型
});

const formData = reactive({
    name: '',
    type: ''
});

const loading = ref<boolean>(false);
const dialogVisible = ref<boolean>(false);
const searchFormRef = ref<InstanceType<typeof FormInstance>>();
const formRef = ref<InstanceType<typeof FormInstance>>();
const currentUpdateId = ref<undefined | number>(undefined);
const tableData = ref<GetTableData[]>([]);
const {paginationData, handleCurrentChange, handleSizeChange} = usePagination();

// 表单 rules 规则
const formRules = reactive<InstanceType<typeof FormRules>>({
    name: [{required: true, trigger: 'blur', message: '请输入名称'}],
    type: [{required: true, trigger: 'change', message: '请输入类型'}]
});

const getTagType = (type: any) => {
    return enumTagType[type] || '';
};

// 新建/编辑 确认按钮
const handleCreate = () => {
    formRef.value?.validate((valid: boolean, fields: any) => {
        if (valid) {
            if (currentUpdateId.value === undefined) {
                addTableDataApi(formData)
                    .then(({data: res}) => {
                        if (res.code === 100000) {
                            ElMessage.success('新增成功');
                            getTableData();
                        } else {
                            ElMessage.error(res.data);
                        }
                    })
                    .finally(() => {
                        dialogVisible.value = false;
                    });
            } else {
                updateTableDataApi({
                    id: currentUpdateId.value,
                    ...formData
                })
                    .then(({data: res}) => {
                        if (res.code === 100000) {
                            ElMessage.success('修改成功');
                            getTableData();
                        } else {
                            ElMessage.error(res.data);
                        }
                    })
                    .finally(() => {
                        dialogVisible.value = false;
                    });
            }
        } else {
            console.error('表单校验不通过', fields);
        }
    });
};

// 删除
const handleDelete = (row: GetTableData) => {
    ElMessageBox.confirm(`删除后不可恢复, 你还要继续吗?`, '确认删除类型', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            deleteTableDataApi(row.id).then(({data: res}) => {
                if (res.code === 100000) {
                    ElMessage.success('删除成功');
                    getTableData();
                } else {
                    ElMessage.error(res.data);
                }
            });
        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '删除失败, 请重试'
            });
        });
};

// 新建
const handleAdd = () => {
    resetForm();
    dialogVisible.value = true;
};

// 编辑
const handleUpdate = (row: GetTableData) => {
    const {id, name, type} = row;
    currentUpdateId.value = id;
    Object.assign(formData, {name, type});
    dialogVisible.value = true;
};

// 查询列表数据
const getTableData = () => {
    loading.value = true;
    const {name, type} = searchData;
    const newItem = {
        name,
        type,
        page: paginationData.currentPage,
        size: paginationData.pageSize
    };
    getTableDataApi(newItem)
        .then(({data: res}) => {
            if (res.code === 100000) {
                const {content, number, totalElements} = res.data;
                tableData.value = content;
                paginationData.currentPage = number;
                paginationData.total = totalElements;
            }
        })
        .catch(() => {
            tableData.value = [];
        })
        .finally(() => {
            loading.value = false;
        });
};

// 查询
const handleSearch = () => {
    paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1);
};

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, {immediate: true});

// 重置查询表单
const resetSearch = () => {
    searchFormRef.value?.resetFields();
    handleSearch();
};

// 重置新建/编辑表单
const resetForm = () => {
    currentUpdateId.value = undefined;
    formRef.value?.resetFields();
    formData.name = '';
    formData.type = '';
};
</script>

<style lang="less" scoped></style>
